# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name：     icris
   Description :
   Author :       wuqianyong
   date：          2020/7/13
-------------------------------------------------
   Change Activity:
                   2020/7/13:
-------------------------------------------------
"""
__author__ = 'wuqianyong'

import datetime, time
from extra_apps.common_log import Log
from base.crawler_task import CrawlerTask
from selenium.webdriver.support.ui import Select
import json


class GOVTask(CrawlerTask):
    def __init__(self):
        super().__init__()
        # 下面会覆盖 父类的 设置
        self.name = "GOV"
        self.start_url = "https://www.gov.hk/en/residents/taxes/etax/services/application_for_supply_of_information_on_the_br.htm"

    def input_yzm(self):
        """输入验证码"""
        while True:
            time.sleep(2)
            input("Please enter the verification code (case sensitive) in browser (enter for next step)")
            Log.info("Click Submit")
            try:
                self.chrome.find_element_by_xpath("//*[@id='buttonArea']/div/a[@class='buttondefault']").click()
            except:
                Log.info("You've ordered the submit")
            time.sleep(2)
            if self.chrome.find_elements_by_xpath('//*[@id="contentPanel"]/div/div[1]/div'):
                Log.info("Incorrect verification code input")
                # self.chrome.find_element_by_xpath('//input[@type="button"]').click()
            else:
                Log.info("The verification code is input correctly")
                break

    def handle_first_notice(self):
        """delete"""
        if self.chrome.current_url == "https://www.icris.cr.gov.hk/preDown.html":
            Log.info("step[1.2]: Is the current page the target page")
            # self.chrome

    def parse_find_result(self):
        """解析公司查询结果"""
        tr_list = self.chrome.find_elements_by_xpath('//*[@id="cont_table"]/tbody/tr[2]/td/table/tbody/tr')
        if len(tr_list) == 2:
            Log.info("There is only one query result, and it will go to the next step automatically")
            td_list = tr_list[1].find_elements_by_xpath("td")
            Log.info("click：{}".format(td_list[1].text))
            td_list[1].click()
            time.sleep(2)
        else:
            Log.info("Human intervention is needed")
            time.sleep(1)
            # Log.info(msg="人工介入：自己选择")
            input("[manual intervention] select by yourself (enter key for next step)")
    def get_company_info(self):
        tr_list = self.chrome.find_elements_by_xpath(
            '//*[@id="cont_table"]/tbody/tr[2]/td/table/tbody/tr')
        item = dict()
        for tr in tr_list:
            val_list = [x.text for x in tr.find_elements_by_xpath("td")]
            item[val_list[0][:-1]] = val_list[1]
        self.item_list.append(item)
        self.save_to_excel()

    def find_company_name(self, company_name):
        """company_name"""
        Log.info("substep[0]:find {}".format(company_name))
        self.chrome.find_element_by_name("companyName").send_keys(company_name)
        time.sleep(2)
        sl = Select(self.chrome.find_element_by_name("businessAddArea"))
        sl.select_by_value("A")
        Log.info("Input verification code")
        self.input_yzm()
        # TODO 对结果进行一个 判断，如果单条跳过 人工介入
        self.parse_find_result()
        # //*[@id="cont_table"]/tbody/tr[2]/td/table/tbody/tr
        Log.info("save info to desktop excel")
        self.get_company_info()
        Log.info("Click Application for supply of information")
        self.chrome.find_element_by_xpath("//*[@id='buttonArea']/div/a[@class='buttondefault']").click()
        time.sleep(3)
        Log.info("Choose the first one Electronic extract of information on the Business Registe，and next step")
        self.chrome.find_element_by_xpath("//input[@value='EI']").click()
        time.sleep(1)
        self.chrome.find_element_by_xpath("//*[@id='buttonArea']/div/a[@class='buttondefault']").click()
        time.sleep(3)
        self.chrome.find_element_by_xpath("//*[@id='buttonArea']/div/a[@class='buttondefault']").click()
        time.sleep(2)

    def main_proc(self, company_list):
        """主流程"""

        Log.info(self.start_url)
        self.chrome.get(self.start_url)
        time.sleep(4)
        while True:
            if "Apply now" not in self.chrome.page_source:
                Log.info("no Apply now")
                time.sleep(10)
            else:
                break
        Log.info("step[1]:Click Apply now")

        self.chrome.find_element_by_link_text("Apply now").click()
        time.sleep(3)

        Log.info("switch windows")
        handles = self.chrome.window_handles
        new_handle = [x for x in handles if x != self.chrome.current_window_handle][0]
        self.chrome.switch_to.window(new_handle)
        time.sleep(6)
        while True:
            if "Continue" not in self.chrome.page_source:
                Log.info("no Continue")
                time.sleep(10)
            else:
                break
        Log.info("step[2]:Click Continue")
        try:
            self.chrome.find_element_by_xpath("//input[@value='Continue']").click()
        except:
            time.sleep(5)
            self.chrome.find_element_by_xpath("//input[@value='Continue']").click()
            pass
        time.sleep(3)
        Log.info("switch windows")
        handles = self.chrome.window_handles
        if len(handles) == 3:
            self.chrome.switch_to.window(handles[-1])
        Log.info("step[3]:Click Begin Application")
        time.sleep(3)
        try:
            self.chrome.switch_to.frame(self.chrome.find_element_by_xpath('//frame'))
        except:
            Log.info(self.chrome.page_source)
            time.sleep(3)
        time.sleep(2)
        self.chrome.find_element_by_xpath("//*[@id='buttonArea']/div/a").click()
        Log.info("step[4]:Click I have read")
        self.chrome.find_element_by_xpath("//*[@id='buttonArea']/div/a[@class='buttondefault']").click()

        Log.info("step[5]: Select service")
        self.chrome.find_element_by_xpath('//input[@value="BRE"]').click()
        Log.info("step[6]:Click Continue")
        self.chrome.find_element_by_xpath("//*[@id='buttonArea']/div/a[@class='buttondefault']").click()
        Log.info("step[7]: Enter the company's full name and address range")
        for i, company_name in enumerate(company_list):
            self.find_company_name(company_name=company_name)
            if i + 1 != len(company_list):
                Log.info("-------------------------------")
                Log.info("need find next company")
                self.chrome.find_element_by_xpath("//*[@id='buttonArea']/div/a[@class='buttondefault']").click()
                # 点击back
                time.sleep(2)
                self.chrome.find_element_by_link_text("Back").click()
                time.sleep(3)
                self.chrome.find_element_by_xpath("//*[@id='buttonArea']/div/a[@class='buttondefault']").click()
                time.sleep(2)

        Log.info("All companies have been checked！！！")
        self.chrome.find_element_by_xpath("//*[@id='buttonArea']/div/a[@class='button']").click()
        time.sleep(2)
        # self.chrome.find_element_by_xpath("//*[@id='buttonArea']/div/a[@class='buttondefault']").click()
        time.sleep(2)
        Log.info("Input Applicant")
        self.chrome.find_element_by_xpath("//input[@name='tbName']").send_keys("bank")
        time.sleep(2)
        self.chrome.find_element_by_xpath("//*[@id='buttonArea']/div/a[@class='buttondefault']").click()
        time.sleep(2)
        Log.info("Click Pay now")
        self.chrome.find_element_by_xpath("//*[@id='buttonArea']/div/a[@class='buttondefault']").click()
        input("Please continue [manual intervention] for payment and other operations (enter key for next step)")
        time.sleep(1)
        input("To confirm whether to save the order number information, press enter to finish the program 30 seconds later")
        time.sleep(30)

    def run(self):

        Log.info("Load the list of companies to be queried")
        company_list = self.get_company_list(self.name)
        Log.info("The list of companies to be queried is:\n{}".format(company_list))
        if company_list:
            self.main_proc(company_list)
        Log.info("Close {} services....".format(self.name))
        time.sleep(3)
        self.chrome.quit()
